package com.jk1.bianligou.blg.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.jk1.bianligou.blg.domain.constant.Constants.USER_ATTRIBUTE;

/**
 * @author WHH
 */
public class UserUtils {

    /**
     * 获取当前登录用户ID（线程安全版）
     */
    public static Long getLoginUserId(HttpServletRequest request) {
        if (request == null) {
            ThrowUtils.throwIfNotLogin();
        }
        // 使用getSession(false)避免自动创建新session
        HttpSession session = request.getSession(false);
        if (session == null) {
            ThrowUtils.throwIfNotLogin();
        }
        // 同步块保证线程安全
        synchronized (session) {
            Object userId = session.getAttribute(USER_ATTRIBUTE);
            if (userId == null) {
                ThrowUtils.throwIfNotLogin();
            }
            return (Long) userId;
        }
    }
}